import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import styles from './index.module.scss'
import io from 'socket.io-client'
import { getTokenInfo } from '@/utils/storage'
import { useDispatch } from 'react-redux'
import { getUser } from '@/store/actions/profile'

const Chat = () => {
  const dispatch = useDispatch()
  // 聊天记录
  const [messageList, setMessageList] = useState([
    // 放两条初始消息
    { type: 'robot', text: '亲爱的用户您好，小智同学为您服务。' },
    { type: 'user', text: '你好' },
  ])
  // 用户信息
  const user = useSelector((state) => state.profile.user)

  // 输入框内容
  const [msg, setMsg] = useState('')

  const clientRef = useRef(null)

  const listRef = useRef(null)

  // 添加
  const onKeyUp = (e) => {
    if (e.keyCode !== 13) return
    if (!msg) return
    setMessageList([...messageList, { type: 'user', text: msg }])
    clientRef.current.emit('message', {
      msg,
      timestamp: Date.now(),
    })
    setMsg('')
  }

  useEffect(() => {
    dispatch(getUser())
    // 创建客户端实例
    const client = io('http://geek.itheima.net', {
      query: {
        token: getTokenInfo().token,
      },
      transports: ['websocket'],
    })

    clientRef.current = client

    // 监听连接成功的事件
    client.on('connect', () => {
      setMessageList((messageList) => [
        ...messageList,
        { type: 'robot', text: '建立连接成功' },
      ])
    })
    // 接收到服务器事件
    client.on('message', (data) => {
      setMessageList((messageList) => [
        ...messageList,
        { type: 'robot', text: data.msg },
      ])
    })

    // 在组件销毁时关闭 socket.io 的连接
    return () => {
      client.close()
    }
  }, [dispatch])

  // 滚动条滚动到底部
  useEffect(() => {
    listRef.current.scrollTop =
      listRef.current.scrollHeight - listRef.current.offsetHeight
  }, [messageList])

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header">小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={listRef}>
        {messageList.map((item, index) => {
          // 小智
          if (item.type === 'robot') {
            return (
              <div className="chat-item" key={index}>
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{item.text}</div>
              </div>
            )
            // 用户
          } else {
            return (
              <div className="chat-item user" key={index}>
                <img
                  src={
                    user.photo ||
                    'http://toutiao.itheima.net/images/user_head.jpg'
                  }
                  alt=""
                />
                <div className="message">{item.text}</div>
              </div>
            )
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          className="no-border"
          placeholder="请描述您的问题"
          value={msg}
          onChange={(e) => setMsg(e.target.value)}
          onKeyUp={onKeyUp}
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
